﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace LibUpdate
{
    /// <summary>
    /// http模式下载文件
    /// </summary>
    internal class HttpDownFile : LibUpdate.IDownFile
    {
        /// <summary>
        /// 身份标识
        /// </summary>
        public string Identity{ get; set; }
        /// <summary>
        /// 当前处理版本
        /// </summary>
        public Version Version { get; set; }
        /// <summary>
        /// 获取设置
        /// </summary>
        public UpdateConfig config { get; set; }
        private System.Net.HttpWebResponse Conntion;

        /// <summary>
        /// 下载状态通知
        /// </summary>
        public event FileDownStatusChangedHandler DownStatuesChange;

        /// <summary>
        /// 下载状态通知
        /// </summary>
        public event FileDownProgressChangedHandler DownProgressChange;
       
  
        /// <summary>
        /// 开始下载
        /// </summary>
        public void BeginDown(File file)
        {
            try {
                //通知开始下载该文件
                DownStatusEvt(file, FileDownState.Open, null);

                string url;
                if (file.Type == FileType.UpdateInfoFile) {
                    url = config.ServerPath + "/" + file.FileName;
                }
                else {
                    url = config.ServerPath + Version.Directory.Replace("\\", "/") + file.Path.Replace("\\", "/") + "/" + file.FileName;
                }
                Uri u = new Uri(url);

                //创建一个http请求
                HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(u);
               
                //获得http回应
                Conntion = (HttpWebResponse)myWebRequest.GetResponse();

                using (System.IO.Stream st = Conntion.GetResponseStream()) {
                    if (HttpStatusCode.OK == Conntion.StatusCode) {
                        //文件大小
                        file.Size = Conntion.ContentLength;
                        //正在下载
                        DownStatusEvt(file, FileDownState.Down, null);
                        //写入文件，存入地址为：升级文件目录+版本目录+文件在系统中本身的目录+文件名
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Get_Save_FilePath(file))) {
                            System.IO.BinaryWriter bs = new System.IO.BinaryWriter(sw.BaseStream);

                            int byte_length = 512;
                            int readCount=0;
                            long totalDownloaded=0;
                            byte[] filebyte = new byte[byte_length];
                            int preProgress=0;
                            while ((readCount=st.Read(filebyte, 0, byte_length)) > 0)
                            {
                                totalDownloaded = totalDownloaded + readCount;
                                bs.Write(filebyte, 0, readCount);
                                int progress = (int)((((double)totalDownloaded) / file.Size) * 100);
                                //下载进度通知
                                if (preProgress + 1 <= progress)
                                {
                                    preProgress = progress;
                                    DownProgressEvt(file, totalDownloaded, progress);

                                }
                            }
                            //关闭文件流
                            sw.Close();
                            st.Close();
                            bs.Close();
                            if (myWebRequest != null)
                            {
                                myWebRequest.Abort();
                            }
                        }
                        //下载完成
                        DownStatusEvt(file, FileDownState.End, null);
                    }
                    else {
                        //下载失败
                        DownStatusEvt(file, FileDownState.Error, null);
                    }
                }
            }
            catch (Exception e) {
                //下载失败
                DownStatusEvt(file, FileDownState.Error, null);
            }
        }

        /// <summary>
        /// 获得下载文件的存放路径
        /// </summary>
        /// <param name="file"></param>
        /// <returns>返回路径</returns>
        private string Get_Save_FilePath(File file)
        {
            if (file.Type == FileType.UpdateInfoFile)
            {
                return config.ApplictionPath + Base.UpdatePath + "\\" + file.FileName;
            }
            else
            {
                if (!System.IO.Directory.Exists(config.ApplictionPath + Base.UpdatePath + Version.Directory + file.Path))
                {
                    System.IO.Directory.CreateDirectory(config.ApplictionPath + Base.UpdatePath + Version.Directory + file.Path);
                }
                return config.ApplictionPath + Base.UpdatePath + Version.Directory + file.Path + "\\" + file.FileName;
            }
        }

     


        /// <summary>
        /// 触发下载状态事件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="count"></param>
        /// <param name="state"></param>
        private void DownStatusEvt(File file,FileDownState state,string errinfo)
        {
            //引发数据下载事件
            FileDownStatusChangedEvent di = new FileDownStatusChangedEvent();
            di.State = state;
            di.File = file;
            if (state == FileDownState.Error)
            {
                di.ErrInfo = errinfo;
            }
            DownStatuesChange(di);
        }

        /// <summary>
        /// 触发下载进度事件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="count"></param>
        /// <param name="state"></param>
        private void DownProgressEvt(File file, long downingSize, int progrees)
        {
            //引发数据下载事件
            FileDownProgressChangedEvent di = new FileDownProgressChangedEvent();
            di.DowningSize = downingSize;
            di.Progrees = progrees;
            di.File = file;
            DownProgressChange(di);
        }


        /// <summary>
        /// 身份验证
        /// </summary>
        public bool Validate_Identity()
        {
            return true;
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        public bool ConnetionServer()
        {
            return true;
        }

      
    }
}
